/**
 * @version: V1.0
 * @Title: Test07_MergeTwoSortedLinkedList.java
 * @Description:
 * @author wangshipeng
 * @date 2022-01-17 23:41
 * @Copyright: 2022-01-17
 */

package com.peng.linkedlist;

/**
 * @author wangshipeng
 * @ClassName: Test07_MergeTwoSortedLinkedList
 * @Description:
 * @date 2022-01-17 23:41
 */
public class Test07_MergeTwoSortedLinkedList {

    public static Node mergeTwoSortedLinkedList(Node head1, Node head2) {
        if (head1 == null || head2 == null) {
            return head1 == null ? head2 : head1;
        }
        //小值的链表头作为头
        Node head = head1.value <= head2.value ? head1 : head2;
        Node cur1 = head.next;
        Node cur2 = head == head1 ? head2 : head1;
        Node pre = head;
        while (cur1 != null && cur2 != null) {
            if (cur1.value <= cur2.value) {
                pre.next = cur1;
                cur1 = cur1.next;
            } else {
                pre.next = cur2;
                cur2 = cur2.next;
            }
            pre = pre.next;
        }

        //跳到最后，cur1或者cur2肯定有一个不为空的，那个不为空就是最大的值，直接指向即可
        pre.next = cur1 != null ? cur1 : cur2;

        return head;
    }

}
